package com.peanut.baby.mvp.bbs.detail;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.comm.MyViewPagerAdapter;
import com.peanut.baby.db.DBManager;
import com.peanut.baby.model.Ad;
import com.peanut.baby.model.BBSComment;
import com.peanut.baby.model.BBSMoment;
import com.peanut.baby.model.MomentRel;
import com.peanut.baby.model.Task;
import com.peanut.baby.model.TaskDBRecord;
import com.peanut.baby.mvp.bbs.BBSBaseActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.profile.ProfileActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.baby.util.ShareUtil;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.util.TimeUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.peanut.devlibrary.widget.pullrecycle.PullRecyclerView;
import com.peanut.devlibrary.widget.pullrecycle.layoutmanager.XLinearLayoutManager;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by anonymouslystudio on 2017/7/28.
 */

public class BBSMomentDetailActivity extends BBSBaseActivity
        implements TitleLayout.OnTitleClickListener,
        PullRecyclerView.OnRecyclerRefreshListener,
        View.OnClickListener, BBSMomentDetailContract.View,
        TextView.OnEditorActionListener,ViewPager.OnPageChangeListener {

    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.listview)
    PullRecyclerView listview;
    @BindView(R.id.normal_edit)
    EditText normalEdit;


    TextView detailTitle;
    TextView detailNick;
    TextView detailTime;
    ImageView detailAvatar;
    TextView detailCmtCount;
    TextView detailCmtCount1;
    //    TextView     detailCmtWriter;
    LinearLayout detailContent;
    WebView detailWeb;
    LinearLayout authContainer;


    private Runnable scrollRunnable;
    private boolean resumed = false;
    private Handler handler = new Handler();

    @BindView(R.id.input_container)
    LinearLayout inputContainer;


    private String momentId = "";
    private BBSMomentDetailPresenter presenter;
    private BBSMoment moment;
    private List<BBSComment> comments;
    private BBSCommentRecyclerAdapter adapter;
    private int pageNo = 1;
    private int pageSize = 10;


    //rel
    LinearLayout relContainer;
    ViewPager relBViewpager;
    RadioGroup relBRadiogroup;
    FrameLayout relBFrame;
    TextView relPre;
    TextView relNext;
    TextView relPartner;
    LinearLayout relQaContainer;
    protected MyViewPagerAdapter relBAdapter;                      //banner适配器
    protected List<View> relViews;


    /**
     * @param ctx
     */
    public static void start(Context ctx, String bbsId) {
        ctx.startActivity(new Intent(ctx, BBSMomentDetailActivity.class).putExtra("id", bbsId));
    }

    public static void start(Context ctx, BBSMoment moment) {
        ctx.startActivity(new Intent(ctx, BBSMomentDetailActivity.class).putExtra("moment", moment));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bbs_detail);
        ButterKnife.bind(this);

        if (getIntent().hasExtra("id")) {
            momentId = getIntent().getStringExtra("id");
        }

        if (getIntent().hasExtra("moment")) {
            moment = (BBSMoment) getIntent().getSerializableExtra("moment");
            momentId = moment.id + "";
        }

        if (StringUtil.isNullOrEmpty(momentId)) {
            finish();
            return;
        }
        presenter = new BBSMomentDetailPresenter(this, this);
        initView();
    }

    private void initView() {
        title.setTitle("内容详情");
        title.setOnTitleClickedListener(this);
        title.setTitleRightTextDrawable("", R.drawable.icon_share);
        title.setTitleRightVisibility(true);

        View header = LayoutInflater.from(this).inflate(R.layout.layout_bbs_detail_header, null);
        detailTitle = (TextView) header.findViewById(R.id.detail_title);
        detailAvatar = (ImageView) header.findViewById(R.id.detail_avatar);
        detailNick = (TextView) header.findViewById(R.id.detail_nick);
        detailTime = (TextView) header.findViewById(R.id.detail_time);
        detailCmtCount = (TextView) header.findViewById(R.id.detail_cmt_count);
        detailCmtCount1 = (TextView) header.findViewById(R.id.detail_cmt_count1);

        authContainer = (LinearLayout) header.findViewById(R.id.author_container);

        detailContent = (LinearLayout) header.findViewById(R.id.detail_content);

        //rel
        relContainer = header.findViewById(R.id.rel_container);
        relBViewpager = header.findViewById(R.id.rel_banner_viewpager);
        relBRadiogroup = header.findViewById(R.id.rel_banner_radiogroup);
        relBFrame = header.findViewById(R.id.rel_banner_frame);
        relPre = header.findViewById(R.id.rel_pre);
        relNext = header.findViewById(R.id.rel_next);
        relPartner = header.findViewById(R.id.rel_partner);
        relQaContainer = header.findViewById(R.id.rel_qa_container);
        fixRelBannerSize();



        configureWeb();

        detailAvatar.setOnClickListener(this);
        normalEdit.setOnEditorActionListener(this);

        listview.enablePullRefresh(false);
        listview.enableLoadMore(true);
        listview.setOnRecyclerRefreshListener(this);
        comments = new ArrayList<>();
        adapter = new BBSCommentRecyclerAdapter(this, comments);
        listview.setLayoutManager(new XLinearLayoutManager(this));
        listview.setAdapter(adapter);
        listview.addHeaderView(header);


        scrollRunnable = new Runnable() {
            @Override
            public void run() {
                if (relBAdapter != null && relBAdapter.getCount() > 0) {
                    int currentIndex = relBViewpager.getCurrentItem();
                    int pos = currentIndex + 1;
                    if (pos > relBAdapter.getCount() - 1) {
                        pos = 0;
                    }

                    relBViewpager.setCurrentItem(pos);
                }
                if (resumed) {
                    handler.postDelayed(scrollRunnable, 3000);
                }
            }
        };

        if (moment != null) {
            bindView();
        } else {
            presenter.getMomentDetail(momentId);
        }

        presenter.getPostRel(momentId);

        reloadComment();
    }

    private void fixRelBannerSize(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) relBFrame.getLayoutParams();
        params.height = InitManager.getInstance().getScreenWidth() * 3 / 5;
        relBFrame.setLayoutParams(params);
    }


    private void bindView() {
        if (moment != null) {
            //author info
            ImageLoader.getInstance().loadImageView(BBSMomentDetailActivity.this, moment.avatar, detailAvatar);
            detailNick.setText(moment.nickname);
            detailTime.setText(com.peanut.baby.util.TimeUtil.getDisplayTimeMillis(moment.updateTime));
            detailCmtCount.setText(moment.commentCount + "");
            detailCmtCount1.setText(moment.commentCount + "");


            detailTitle.setText(moment.title);
            detailWeb.loadData(getFixHtmlContent(moment.content), "text/html; charset=UTF-8", null);
            detailContent.removeAllViews();
            detailContent.addView(detailWeb);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        resumed = true;
        handler.postDelayed(scrollRunnable, 3000);

    }

    @Override
    protected void onPause() {
        super.onPause();
        resumed = false;
        handler.removeCallbacks(scrollRunnable);
    }


    private String getFixHtmlContent(String body) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + body + "</body></html>";
    }

    private void configureWeb() {
        detailWeb = (WebView) LayoutInflater.from(this).inflate(R.layout.layout_bbs_detail_web, null);
        detailWeb.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        detailWeb.setVerticalScrollBarEnabled(false);
        detailWeb.setVerticalScrollbarOverlay(false);
        detailWeb.setHorizontalScrollBarEnabled(false);
        detailWeb.setHorizontalScrollbarOverlay(false);
        detailWeb.getSettings().setDefaultTextEncodingName("utf-8");
        detailWeb.setWebViewClient(new BWebViewClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            detailWeb.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        } else {
            detailWeb.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
    }

    class BWebViewClient extends WebViewClient{

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String s) {
            if(!StringUtil.isNullOrEmpty(s)){
                WebViewActivity.start(BBSMomentDetailActivity.this,s,"内容详情",moment.imgUrl);
            }
            return true;
        }
    }


    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {
        new BaseDialog().showShareDialog(BBSMomentDetailActivity.this, new BaseDialog.OnShareItemSelected() {
            @Override
            public void onShareItemSelected(int item) {
                String platName = "";
                if (item == BaseDialog.OnShareItemSelected.TYPE_MOMENT) {
                    platName = WechatMoments.NAME;
                } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIXIN) {
                    platName = Wechat.NAME;
                } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIBO) {
                    platName = SinaWeibo.NAME;
                } else if (item == BaseDialog.OnShareItemSelected.TYPE_QQ) {
                    platName = QQ.NAME;
                }
                if (StringUtil.isNullOrEmpty(platName)) {
                    return;
                }
                if(moment == null){
                    return;
                }
                ShareUtil.getInstance().shareMoment(moment, platName, new ShareUtil.IShareCallback() {
                    @Override
                    public void onShareFinished(boolean isSuccess, String platformName, String failReason) {
                        showToast(isSuccess ? "分享成功" : failReason);
                        if (isSuccess && InitManager.getInstance().getUser() != null) {
                            TaskDBRecord record = DBManager.getInstance().getTaskRecord(Integer.parseInt(InitManager.getInstance().getUserId()), TimeUtil.getCurrentDate());
                            record.shareMomentCount++;
                            if (record.shareMomentCount > 1) {
                                record.shareMomentCount = 1;

                            } else {
                                presenter.sharePoint(momentId);
                            }
                            DBManager.getInstance().updateTaskRecord(record);
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onTitleClicked() {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.detail_avatar:
                if (moment != null) {
                    ProfileActivity.start(this, moment.userId + "");
                }

                break;
//            case R.id.comment_write:
//                if(inputContainer.getVisibility() != View.VISIBLE){
//                    inputContainer.setVisibility(View.VISIBLE);
//                }else{
//                    inputContainer.setVisibility(View.GONE);
//                }
//                break;
        }
    }

    @Override
    public void onDetailGet(BBSMoment moment) {
        this.moment = moment;
        bindView();
    }

    @Override
    public void onCommentsGet(List<BBSComment> _comments) {
        stopRefreshAndLoadMore();
        if (pageNo == 1) {
            comments.clear();
        }
        if (_comments != null && !_comments.isEmpty()) {
            comments.addAll(_comments);
        }
        adapter.notifyDataSetChanged();
        listview.enableLoadMore(_comments != null && _comments.size() >= pageSize);
    }

    @Override
    public void onGetCommentsFailed(String reason) {
        stopRefreshAndLoadMore();
    }

    @Override
    public void onGetDetailFailed(String reason) {
        dismissProgressDialog();
        showToast("获取内容失败 " + reason);
        finish();
    }

    @Override
    public void onSendCommentSuccess(BBSComment comment) {

        TaskDBRecord record = DBManager.getInstance().getTaskRecord(Integer.parseInt(InitManager.getInstance().getUserId()), TimeUtil.getCurrentDate());
        record.replyMomentCount++;
        if (record.replyMomentCount > Task.MAX_REPLY_MOMENTS) {
            record.replyMomentCount = Task.MAX_REPLY_MOMENTS;
        }

        DBManager.getInstance().updateTaskRecord(record);

        dismissProgressDialog();
        hideSoftKeyboard();
        normalEdit.setText("");
        moment.commentCount++;
        detailCmtCount.setText(moment.commentCount + "");
        detailCmtCount1.setText(moment.commentCount + "");
        reloadComment();
    }

    private void reloadComment() {
        pageNo = 1;
        presenter.getComments(pageNo, pageSize, momentId);
    }

    @Override
    public void onSendCommentFailed(String reason) {
        dismissProgressDialog();
        showToast(reason);
    }

    @Override
    public void onSharePointSuccess(String tips) {
        showToast(tips);
    }


    @Override
    public void onPostRelGet(boolean success, MomentRel rel, String failReason) {
        if(!success || rel == null || rel.hasEmpty()){
            relContainer.setVisibility(View.GONE);
        }else{
            relContainer.setVisibility(View.VISIBLE);
            relPre.setOnClickListener(null);
            relNext.setOnClickListener(null);
            relPartner.setOnClickListener(null);

            initRelBanners(rel.goodsList);
            if(rel.preUrl != null && rel.preUrl.id > 0){
                relPre.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BBSMomentDetailActivity.start(BBSMomentDetailActivity.this,rel.preUrl.id+"");
                    }
                });
            }
            if(rel.nextUrl != null && rel.nextUrl.id > 0){
                relNext.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BBSMomentDetailActivity.start(BBSMomentDetailActivity.this,rel.nextUrl.id+"");
                    }
                });
            }
            if(!StringUtil.isNullOrEmpty(rel.hhrUrl)){
                relPartner.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WebViewActivity.start(BBSMomentDetailActivity.this,rel.hhrUrl,"花生好孕优选梦想合伙人","");
                    }
                });
            }
            if(rel.postRel != null && !rel.postRel.isEmpty()){
                initRelPosts(rel.postRel);
            }
        }
    }

    //隐藏推荐的banner
    private void fakeHideRelBanner(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) relBFrame.getLayoutParams();
        params.height = 1;
        relBFrame.setLayoutParams(params);
    }

    //
    private void initRelPosts(List<BBSMoment> moments){
        if(moments == null || moments.isEmpty()){
            return;
        }
        relQaContainer.removeAllViews();
        int len = moments.size();
        for(int i=0;i<len;i++){
            final BBSMoment moment = moments.get(i);
            final View relView = getLayoutInflater().inflate(R.layout.layout_rel_item, null);
            final TextView relText = relView.findViewById(R.id.rel_text);
            relText.setText(moment.title);
            relText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BBSMomentDetailActivity.start(BBSMomentDetailActivity.this,moment.id+"");
                }
            });
            relQaContainer.addView(relView);
        }
    }
    //显示推荐的 banner
    private void initRelBanners(final List<Ad> objs) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (objs == null || objs.isEmpty()) {
                    fakeHideRelBanner();
                    return;
                }
                fixRelBannerSize();
                if (relViews == null) {
                    relViews = new ArrayList<View>();
                }
                relViews.clear();
                relBRadiogroup.removeAllViews();
                int size = objs.size();
                int rightMargin = getResources().getDimensionPixelSize(R.dimen.ad_radio_size);
                for (int i = 0; i < size; i++) {
                    final Ad ad = objs.get(i);
                    final View adView = getLayoutInflater().inflate(R.layout.layout_ad, null);
                    final ImageView img = adView.findViewById(R.id.ad_image);

                    ImageLoader.loadImageView(BBSMomentDetailActivity.this, ad.imgUrl, img);


                    relViews.add(adView);

                    adView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            WebViewActivity.start(BBSMomentDetailActivity.this, ad.htmlUrl, ad.name,ad.imgUrl);
                        }
                    });

                    RadioButton radioButton = new RadioButton(BBSMomentDetailActivity.this);
                    radioButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
                    try {
                        radioButton.setBackgroundDrawable(BBSMomentDetailActivity.this.getResources().getDrawable(R.drawable.selector_ad_radiobutton));
                    } catch (Resources.NotFoundException e) {
                        e.printStackTrace();
                    }
                    RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(rightMargin, rightMargin);
                    if (i != (size - 1)) {
                        params.rightMargin = rightMargin;
                    }
                    relBRadiogroup.addView(radioButton, params);


                }
                ((RadioButton) relBRadiogroup.getChildAt(0)).setChecked(true);
                relBAdapter = new MyViewPagerAdapter(relViews);
                relBViewpager.setAdapter(relBAdapter);
                relBViewpager.setOnPageChangeListener(BBSMomentDetailActivity.this);

            }
        });

    }


    @Override
    public void onPullRefresh() {
        stopRefreshAndLoadMore();
    }

    @Override
    public void onLoadMore() {
        pageNo++;
        presenter.getComments(pageNo, pageSize, momentId);
    }

    private void stopRefreshAndLoadMore() {
        listview.stopLoadMore();
        listview.stopRefresh();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendComment();
            return true;
        }
        return false;
    }

    private void sendComment() {
        if (InitManager.getInstance().getUser() == null) {
            LoginActivity.startForResult(BBSMomentDetailActivity.this);
            return;
        }
        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
            BindMobileActivity.startForResult(BBSMomentDetailActivity.this);
            return;
        }

        String commentString = normalEdit.getText().toString().trim();
        if (StringUtil.isNullOrEmpty(commentString)) {
            showToast("请输入评论内容");
            return;
        }
        showProgressDialog("请稍候...", false);
        presenter.sendComment(momentId, 1, "", commentString);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        ((RadioButton) relBRadiogroup.getChildAt(position)).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
